package hashmapexercise;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-08-01
 * Time: 10:40
 */

/**
 * 单词出现的次数
 */
public class SimplyHashMapExercise {
    public static HashMap<String, Integer> countWords(String[] words) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        for (String x : words) {
            if (hashMap.get(x) == null) {
                //只出现一次
                hashMap.put(x,1);
            }else {
                //出现多次
                int val = hashMap.get(x);
                hashMap.put(x,val+1);
            }

        }
        return hashMap;
    }

    public static void main(String[] args) {
        String[] words = {"ahh", "hehe", "hehe", "hehe"};
        HashMap<String, Integer> map = countWords(words);
        Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
        for (Map.Entry<String, Integer> entry : entrySet) {
            System.out.println("key " + entry.getKey() + "val " + entry.getValue());
        }
    }

}
